/**
 * Created by jiexin on 2017/10/12.
 */

// $("#swipercompany").each(function () {
//    console.log($(this));
//     for (var i=0; i<a.length; i++){
//         var childdiv=$('<div></div>');        //创建一个子div
//         // childdiv.addclass('swiper-slide');    //添加css样式
//         childdiv.text(a[i]);
//         // childdiv.appendto($(this));        //将子div添加到父div中
//         $(this).append(childdiv)
//     }
// });

//公司简称导航
var select_data = 0;
var select_company_name = "四川臻盾";
for (var i=0; i<janename.length; i++){
    var childdiv=$('<div class="swiper-slide swiper-slide-color1"></div>');        //创建一个子div
    childdiv.text(janename[i]);
    $("#swipercompany").append(childdiv);
}

var click_status = 0;
var mySwiper1 = new Swiper ('.swiper-container-1', {
    direction: 'vertical',
    loop:true,
    speed: 200,
    slidesPerView: 5,
    mousewheelControl: true,
    //autoplay:6000,
    //autoplayDisableOnInteraction: true,
    onClick: function(sdata, event){
        if (click_status === 0){
            var divtxt = sdata.slides[sdata.clickedIndex];
            click_status = 1;
            console.log($(divtxt).text());   //获取div间的数据
            if ($(divtxt).text() !== undefined && $(divtxt).text() !== ""){
                select_company_name = $(divtxt).text();
                ajaxOne();
                ajaxTwo();
            }
        }else{
            layer.msg('正在请求数据，稍后');
        }
    }
});


//页面加载后启动
$(document).ready(function(){
    ajaxOne(0);
    ajaxTwo(0);
});


//第一组加载
function ajaxOne(ajaxOneselect) {
    if (ajaxOneselect === 0){
        $.ajax({
            url: "/user-chart-company/",
            dataType: "json",
            type: "POST",
            data: {"return_name":select_company_name, "selectdata":select_data, "serial_number":"01"},
            success: function (return_all_data) {
                data3 = return_all_data["inc_data"];
                newdata = return_all_data["inc_amp"];
                data4 = return_all_data["org_data"];
                newdata2 = return_all_data["org_amp"];
                cpysumbarcreate();
                cpysumpiecreate();
                // var reloadpieoption =cpysumpie_refresh(sumpieoption);
                // cpysumpie.setOption(reloadpieoption)
            }
        })
    }else{
        $.ajax({
            url: "/user-chart-company/",
            dataType: "json",
            type: "POST",
            data: {"return_name":select_company_name, "selectdata":select_data, "serial_number":"01"},
            success: function (return_all_data) {
                data3 = return_all_data["inc_data"];
                newdata = return_all_data["inc_amp"];
                data4 = return_all_data["org_data"];
                newdata2 = return_all_data["org_amp"];
                var newcpyboption = cpysumbar.getOption();
                cpysumbar_refresh(newcpyboption);
                var newcpypoption = cpysumpie.getOption();
                cpysumpie_refresh(newcpypoption);
                click_status = 0
            }
        })
    }
}

function cpysumbar_refresh(s_b_option) {
    s_b_option.series[0].data = newdata2;
    s_b_option.series[1].data = data3;
    s_b_option.series[2].data = data4;
    s_b_option.series[3].data = newdata;
    cpysumbar.setOption(s_b_option);
}

function cpysumpie_refresh(returnoption) {
    console.log(data4,111);
    var sumdata = listsum(data4,2);
    var listdataname = ["导入店铺占比", "上线店铺占比", "臻e盾", "臻中心", "臻护卫", "臻总管"];
    var shoplist=[];
    var userlist=[];
    var sumshoplist = listsum(data4,0, 2);
    returnoption.series[0].data = [{value:Math.abs(data4[1]), name:'店铺占比', selected:true}, {value:sumdata, name:'用户占比'}];
    for ( var i=0; i<=data4.length; i++ ){
        if (i <= 1){
            if (data4[i] !== 0){
                shoplist.push({value:Math.abs(data4[i]), name:listdataname[i]})
            }
        }else if (i === data4.length){
            shoplist.push({value:sumshoplist, name:'invisible', itemStyle : placeHolderStyle});
            userlist.push({value:sumdata, name:'invisible', itemStyle : placeHolderStyle})
        }else{
            if (data4[i] !== 0){
                userlist.push({value:Math.abs(data4[i]), name:listdataname[i]})
            }
        }
    }
    console.log(userlist);
    console.log(shoplist);
    returnoption.series[1].data = userlist;
    returnoption.series[2].data = shoplist;
    cpysumpie.setOption(returnoption);
}

//用户店铺柱形图
// var data3 = [95, 97, 238, 0, 0, 0];
// var newdata = [1095, 1097, 1238, 1000, 1000, 1000];
// var data4 = [-17147, -16816, -25284, -145, -42, -261];
// var newdata2 = [-18147, -17816, -26284, -1145, -1042, -1261];

var data3 = [];
var newdata = [];
var data4 = [];
var newdata2 = [];
function cpysumbarcreate() {
    cpysumbar = echarts.init(document.getElementById('sumbar'));
    var itemStyle = {
        normal: {},
        emphasis: {
            barBorderWidth: 1,
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowOffsetY: 0,
            shadowColor: 'rgba(0,0,0,0.5)'
        }
    };
    var sumbaroption = {
        title: {
            text: '数据汇总'
        },
        tooltip: {
            formatter: function(params) {
                // console.log(params);
                if (params.componentSubType !== "line"){
                    if (params.value < 0) {
                        return params.name + '<br/>总量:' + -params.value
                    } else {
                        return params.name + '<br/>增量:' + params.value
                    }
                }else{
                    if (params.seriesName === "总量"){
                        return params.name + '<br/>总量:' + -data4[params.dataIndex]
                    }else{
                        return params.name + '<br/>增量:' + data3[params.dataIndex]
                    }

                }

            }
        },
        xAxis: {
            name: '分类',
            silent: false,
            type: 'category',
            data: ['导入店铺', '上线店铺', '臻E盾用户', '臻中心用户', '臻护卫用户', '臻总管用户']

        },
        legend: {

            data: ['增量', '总量'],
            y: "bottom"
        },
        yAxis: [{
            show:false,
            scale: true,
            inverse: true,
            name: '人数',
            splitArea: {
                show: false
            },
            axisLabel: {
                formatter: function(value) {
                    if (value < 0) {
                        return -value
                    } else {
                        return value
                    }
                }
            }

        }],
        grid: {
        },
        series: [{
            name: "总量",
            type: "line",
            stack: "总量",
            symbolSize:10,
            symbol:'circle',
            itemStyle: {
                normal: {
                    color: 'red',
                    barBorderRadius: 0
                }
            },
            label:{
                normal: {
                    show: true,
                    position: "top",
                    fontSize: 18,
                    formatter: function(p) {
                        // console.log(p);
                        // return p.value > 0 ? (p.value) : '';
                        return -data4[p.dataIndex]
                    }
                }
            },
            data:newdata2
        },{
            name: '人数',
            type: 'bar',
            stack: 'one',
            itemStyle: itemStyle,
            data: data3
        }, {
            name: '金额',
            type: 'bar',
            stack: 'one',
            itemStyle: itemStyle,
            data: data4
        },
        {
            name: "增量",
            type: "line",
            stack: "增量",
            symbolSize:10,
            symbol:'circle',
            itemStyle: {
                normal: {
                    color: "rgba(251,174,2,1)",
                    barBorderRadius: 0
                }
            },
            label:{
                normal: {
                    show: true,
                    position: "bottom",
                    fontSize: 18,
                    formatter: function(p) {
                        // console.log(p);
                        // return p.value > 0 ? (p.value) : '';
                        return data3[p.dataIndex]
                    }
                }
            },
            data:newdata
        }]
    };
    cpysumbar.setOption(sumbaroption);
}


//用户店铺盘图
var cpysumpie;
var placeHolderStyle;
function cpysumpiecreate() {
    cpysumpie = echarts.init(document.getElementById('sumpie'));
    placeHolderStyle = {
        normal : {
            color: 'rgba(0,0,0,0)',
            label: {show:false},
            labelLine: {show:false}
        },
        emphasis : {
            color: 'rgba(0,0,0,0)'
        }
    };
    var sumpieoption = {
        title: {
            text: '占比汇总'
        },
        grid: {
            top:0,
            left: 0
        },
        tooltip: {
            trigger: 'item',
            position: 'inside',
            formatter:function(obj){
                if(obj.name=="用户占比" || obj.name=="店铺占比"){

                    return  obj.name+": "+obj.value+" ("+obj.percent+"%)";
                }
                else{
                    return  obj.name+": "+obj.value+" ("+obj.percent*2+"%)";
                }
            }
        },
        series: [
            {
                name:'用户店铺占比',
                color: ['#86D560', '#AF89D6'],
                type:'pie',
                selectedMode: 'single',
                center:['54%','55%'],
                radius: [0, '30%'],

                label: {
                    normal: {
                        position: 'inner',
                        fontSize: 12,
                        formatter: function(p) {
                            return p.name + '\n' + p.percent + '%'
                        }
                    }
                },
                labelLine: {
                    normal: {
                        show: false
                    }
                },
                data:[
                    {value:16816, name:'店铺占比', selected:true},
                    {value:25284, name:'用户占比'}
                ]
            },
            {
                clockWise:false,
                name:'用户对比',
                color: ['#86D560', '#AF89D6', '#59ADF3', '#FF999A', '#FFCC67'],
                type:'pie',
                startAngle:'80',
                radius: ['35%', '55%'],
                center : ['48%', '55%'],
                label: {
                    normal: {
                        //position: 'inner',
                        fontSize: 12,
                        formatter: function(p) {
                            if (p.name !== 'invisible'){
                                return p.name + '\n' + p.percent*2 + '%'
                            }
                        }
                    }
                },
                labelLine:{
                    normal: {
                        show: true,
                        length:2,
                        length2:2
                    }
                },
                data:[
                    {value:238, name:'臻e盾增量'},
                    {value:238, name:'invisible', itemStyle : placeHolderStyle}
                ]
            },
            {
                name:'店铺对比',
                color: ['#AF89D6', '#AF89D6', '#59ADF3', '#FF999A', '#FFCC67'],
                type:'pie',
                startAngle:'100',
                radius: ['35%', '55%'],
                center : ['62%', '55%'],
                label: {
                    normal: {
                        position: 'inner',
                        fontSize: 12,
                        formatter: function(p) {
                            if (p.name !== 'invisible'){
                                return p.name + '\n' + p.percent*2 + '%'
                            }
                        }
                    }
                },

                data:[
                    {value:17174, name:'导入店铺占比'},
                    {value:16816, name:'上线店铺占比'},
                    {value:33990, name:'invisible', itemStyle : placeHolderStyle}
                ]
            }
        ]
    };
    cpysumpie_refresh(sumpieoption);
}

//第二组数据
function ajaxTwo(ajaxTwoselect) {
    if (ajaxTwoselect === 0){
        $.ajax({
            url: "/user-chart-edun/",
            dataType: "json",
            type:"POST",
            data: {"return_name":select_company_name, "selectdata":select_data, "serial_number":"02"},
            success: function (returntwodata) {
                console.log(returntwodata);
                Twoline(returntwodata)
            }
        })
    }else{
        $.ajax({
            url: "/user-chart-edun/",
            dataType: "json",
            type:"POST",
            data: {"return_name":select_company_name, "selectdata":select_data, "serial_number":"02"},
            success: function (returntwodata) {
                console.log(returntwodata);
                Twoline(returntwodata)
            }
        })
    }
}

var Twolinechart= echarts.init(document.getElementById('edunline'));
function Twoline(twolinedata) {
    var Twolineoption = {
        title : {
            text: '臻E盾用户数/布撤防量'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                lineStyle: {
                    color: '#57617B'
                }
            }
        },
        legend: {
            icon: 'rect',
            itemWidth: 14,
            itemHeight: 5,
            itemGap: 13,
            data: ['臻e盾用户', '用户布撤防'],
            right: '4%',
            textStyle: {
                fontSize: 12,
                color: '#000'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            boundaryGap: false,
            axisLine: {
                lineStyle: {
                    color: '#57617B'
                }
            },
            data: []
        }],
        yAxis: [{
            type: 'value',
            axisTick: {
                show: false
            },
            axisLine: {
                lineStyle: {
                    color: '#57617B'
                }
            },
            axisLabel: {
                margin: 10,
                textStyle: {
                    fontSize: 14
                }
            },
            splitLine: {
                lineStyle: {
                    color: '#57617B'
                }
            }
        }],
        series: [{
            name: '臻e盾用户',
            type: 'line',
            smooth: true,
            lineStyle: {
                normal: {
                    width: 1
                }
            },
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(137, 189, 27, 0.3)'
                    }, {
                        offset: 0.8,
                        color: 'rgba(137, 189, 27, 0)'
                    }], false),
                    shadowColor: 'rgba(0, 0, 0, 0.1)',
                    shadowBlur: 10
                }
            },
            itemStyle: {
                normal: {
                    color: 'rgb(137,189,27)'
                }
            },
            data: []
        }, {
            name: '用户布撤防',
            type: 'line',
            smooth: true,
            lineStyle: {
                normal: {
                    width: 1
                }
            },
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(219, 50, 51, 0.3)'
                    }, {
                        offset: 0.8,
                        color: 'rgba(219, 50, 51, 0)'
                    }], false),
                    shadowColor: 'rgba(0, 0, 0, 0.1)',
                    shadowBlur: 10
                }
            },
            itemStyle: {
                normal: {
                    color: 'rgb(219,50,51)'
                }
            },
            data: []
        }]
    };
    Twolineoption.xAxis[0].data = twolinedata["edun_line_x"];
    Twolineoption.series[0].data = twolinedata["edun_sql_data"];
    Twolineoption.series[1].data = twolinedata["edun_mog_data"];
    Twolinechart.setOption(Twolineoption)
}

function ajaxThree() {
    $.ajax({
        url: "/user-chart-device/",
        dataType: "json",
        type:"POST",
        // data: {"return_name":select_company_name, "selectdata":select_data, "serial_number":"02"},
        success: function (returnthreedata) {
            console.log(returnthreedata);
            var new_series = create_series(returnthreedata["device_list"], returnthreedata["user_data"]);
            Threebar(returnthreedata["device_list"], returnthreedata["company_list"], new_series)
        }
    })
}
ajaxThree();

var Threebarchart= echarts.init(document.getElementById('threebar'));

function create_series(device_list, new_series) {
    var series = [];
    for (var i = 0; i < device_list.length; i++){
        var threeserie = {
            name: '',
            type: 'bar',
            stack: '1',
            // label: {
            //     normal: {
            //         show: true,
            //         position: 'right',
            //         formatter: function(p) {
            //             return p.data > 0 ? (p.data) : ''
            //         }
            //     }
            // },
            data: []
        };
        threeserie.name = device_list[i];
        threeserie.data = new_series[device_list[i]];
        series.push(threeserie)
    }
    return series
}

function Threebar(device_list, company_list, new_series) {
    var threebaroption = {
        grid: {
            left: '0',
            right: '2%',
            bottom: '3%',
            containLabel: true
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(p) {
                var res = "";
                for (var i=0; i < p.length; i++){
                    if (p[i].data > 0){
                        // res.push({p[i]})seriesName data
                        res = res + p[i].seriesName + ' : ' + p[i].data + ' 位用户' + '</br>'
                    }
                }
                return res
            },
            axisPointer: {
                lineStyle: {
                    color: '#57617B'
                }
            }

        },
        legend: {
            // itemHeight: 14,
            // itemWidth: 20,
            selectedMode: false,
            data: device_list
        },
        xAxis: [{
            show: false,
            type: 'value'
        }],
        yAxis: {
            type: 'category',
            inverse: true,
            axisTick: {
                show: false //隐藏Y轴刻度
            },
            data: company_list
        },
        series: new_series
    };
    Threebarchart.setOption(threebaroption)
}

function ajaxFour() {
    $.ajax({
        url: "/deivce-chart-num/",
        dataType: "json",
        type:"POST",
        // data: {"return_name":select_company_name, "selectdata":select_data, "serial_number":"02"},
        success: function (returnfourdata) {
            console.log(returnfourdata);
            Fourbar(returnfourdata["y_list"], returnfourdata["value_list"])
        }
    })
}
ajaxFour();

var Fourbarchart= echarts.init(document.getElementById('fourbar'));
function Fourbar(four_x_list, four_value_list){
    var fourbaroption = {
        title : {
            text: '设备数量'
        },
        grid: {
            left: '0',
            right: '0',
            bottom: '0',
            containLabel: true
        },
        tooltip : {
            trigger: 'axis'
        },
        xAxis : [
            {
                type : 'category',
                data : four_x_list
            }
        ],
        yAxis : [
            {
                type : 'value'
            }
        ],
        series : [
            {
                name:'数量',
                type:'bar',
                data:four_value_list,
                label:{
                  normal:{
                      show:true,
                      position: 'top',
                      textStyle:{
                          fontSize:20
                      }
                  }
                },
                itemStyle: {
                    normal: {
                        color: function(params) {
                            // build a color map as your need.
                            var colorList = [
                              '#C1232B','#B5C334','#FCCE10','#E87C25','#27727B',
                               '#FE8463','#9BCA63','#FAD860','#F3A43B','#60C0DD',
                               '#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0'
                            ];
                            return colorList[params.dataIndex]
                        }
                    }
                }
            }
        ]
    };
    Fourbarchart.setOption(fourbaroption)
}





///////////////
//通用方法
///////////////
//数组求和
function listsum(listdata, liststart, listend) {
    var sumdata = 0;
    if (listend === undefined){
        listend = listdata.length
    }
    for (var i=liststart; i< listend; i++ ){
        sumdata += Math.abs(listdata[i]);
    }
    return sumdata
}





///////////////
//其他事件
///////////////
// $(".button-my span").on('click', function () {
//     console.log(11111111111111)
//     // console.log(parseInt($(this).id()));
//     // select_data = parseInt($(this).val());
//     // ajaxOne(0);
//     // ajaxTwo(0)
// });
var $oldbutton = $('.button-raised');
function buttonclick(datetype) {
    var $obj;
    select_data = parseInt(datetype);
    if (select_data === 2){
        $obj = $(".button-caution")
    }else if (select_data === 1){
        $obj = $(".button-highlight")
    }else{
        $obj = $(".button-primary")
    }
    $obj.addClass('button-raised');
    $obj.removeClass('button-border');
    $oldbutton.addClass('button-border');
    $oldbutton.removeClass('button-raised');
    $oldbutton = $obj;
    ajaxOne(0);
    ajaxTwo(0)
}



